<template>
  <!-- 文章评论 -->
  <div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <CommentsItem v-for="(item, index) in list" :key="index" :coment="item" />
    </van-list>
  </div>
</template>

<script>
import { getComment } from "@/api/coment.js";
import CommentsItem from "./coment-item.vue";
import bus from "@/utils/eventBus.js";
export default {
  created() {
    this.onLoad();
    bus.$on("addlist", this.getList);
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      offset: null,
      error: false,
    };
  },
  props: {
    articleId: {
      type: [String, Number],
      required: true,
    },
  },
  components: {
    CommentsItem,
  },
  methods: {
    async onLoad() {
      this.loading = true;

      try {
        const { data: res } = await getComment({
          type: "a",
          source: this.articleId,
          offset: this.offset,
          limit: 10,
        });
        // 制造错误 测试
        if (Math.random() > 0.5) {
          // JSON.parse("asd");
        }
        this.list.push(...res.data.results);
        console.log(res.data);
        this.$emit("emitTotal", res.data.total_count);
        this.loading = false;

        this.offset = res.data.last_id;
        // 数据全部加载完成
        if (this.offset === res.data.end_id) {
          this.finished = true;
        }
      } catch (err) {
        this.loading = false;
        this.error = true;
      }

      // 加载状态结束
    },
    // 有兄弟发数据来了
    getList(val) {
      this.list.unshift(val.data.new_obj);
      console.log(this.list);
    },
    beforeDestroy() {
      bus.$off("addlist");
    },
  },
};
</script>

<style lang="less" scoped>
</style>